package com.itsu.integration.service.impl;

import com.alibaba.fastjson.JSON;
import com.itsu.integration.exception.CustomException;
import com.itsu.integration.vo.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.support.ErrorMessage;
import org.springframework.stereotype.Component;

/**
 * 异常处理类
 *
 * @author suben
 * @date 2020/5/2 1:01
 */
@Component
@Slf4j
public class ErrorHandler {


    //Spring 会将发生的异常包装成一个ErrorMessage对象，此对象的payload是具体的exception
    public Response handler(ErrorMessage message) {
        System.err.println(JSON.toJSONString(message.getOriginalMessage()));
        //可以先用一个最大的Exception基类进行强制转换，然后可通过判断不同的Exception类型进行不同的响应对象包装
        Exception exception = (Exception) message.getPayload();
        log.error(exception.getCause().getMessage(), exception.getCause());
        Response response = new Response();
        //因为spring会将发生的异常包装成MessagingException，所以需要先获取到原异常
        if (exception.getCause() != null) {
            exception = (Exception) exception.getCause();
        }
        if (exception instanceof CustomException) {
            response.setMsg("error happened [ 抛出了自定义异常 ]");
        } else if (exception instanceof ArithmeticException) {
            response.setMsg("error happened [ 抛出了数学运行异常 ]");
        } else {
            //默认错误响应对象包装
            response.setMsg("error happened [" + exception.getMessage() + "]");
        }
        return response;
    }
}
